package com.epfresh.activity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputFilter;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.OfferExpandListAdapter;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.PointerInputFilter;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.keyboard.KeyboardUtil;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.OfferMarkBean;
import com.epfresh.bean.OfferMyList;
import com.epfresh.bean.OfferDtoBean;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.DataManager;
import com.epfresh.utils.FormatUtil;
import com.epfresh.views.MultiStateView;
import com.epfresh.views.dialog.OfferTipsDialog;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/*问价列表*/
public class OfferListActivity extends BaseActivity {
    private String marketId = "";

    private View vBottom;
    private ImageView ivCheck;

    private TextView tvAll;
    private TextView tvBtn;

    private PtrMdFrameLayout frameLayout;

    private MultiStateView msView;

    private ExpandableListView lv;

    private OfferExpandListAdapter adapter;
//    private List<String> popupMenuItemList = new ArrayList<>();

    //    private PopupList popupList = new PopupList();
    private List<OfferMarkBean> groupList = new ArrayList<>();
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout ptrFrameLayout, View view, View view1) {
            return PtrDefaultHandler.checkContentCanBePulledDown(ptrFrameLayout, lv, view1);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {

            refresh();

        }
    };

    public void refresh() {
            requestCartList();
    }


    KeyboardUtil keyboardUtil;
    EditText etInput;
    //键盘页面
    private View llKeyboard;
    //键盘背景
    private View llKeyboardBg;
    View ivOfferClear;

    protected void updateKeyboard() {
        if (!keyboardUtil.isKeyboardShowing()) {
            llKeyboard.setVisibility(View.GONE);
            llKeyboardBg.setVisibility(View.GONE);
            etInput.setVisibility(View.GONE);

        } else {
            llKeyboard.setVisibility(View.VISIBLE);
            llKeyboardBg.setVisibility(View.VISIBLE);
            llKeyboardBg.setBackgroundColor(0x60000000);
            //etInput.setText("");
            etInput.setVisibility(View.VISIBLE);
        }
    }

    public void openOfferDialog(final OfferMarkBean.ProductListBean cartGood,final int fatherPosition,final int childPosition) {
        //商品数量
        ivOfferClear = findViewById(R.id.iv_offer_clear);
        llKeyboard = findViewById(R.id.ll_keyboard);
        llKeyboardBg = findViewById(R.id.v_keyboard_bg);
        etInput = (EditText) findViewById(R.id.et_input);
        PointerInputFilter cashierInputFilter = new PointerInputFilter();
        cashierInputFilter.MAX_VALUE = 99999.99d;
        etInput.setFilters(new InputFilter[]{cashierInputFilter});
        ivOfferClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                etInput.setText("");
            }
        });

        llKeyboardBg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyboardUtil.hideKeyboard();
                updateKeyboard();
            }
        });
        keyboardUtil = new KeyboardUtil(this);
        keyboardUtil.attachTo(etInput);

        keyboardUtil.setOnCancelClick(new KeyboardUtil.onCancelClick() {
            @Override
            public void onCancellClick() {
                updateKeyboard();
            }
        });
        etInput.setText(FormatUtil.subZeroAndDot(cartGood.getProductCount()+""));
        //etInput.getSelectionStart();
        etInput.setSelection(etInput.getText().toString().length());
        keyboardUtil.setOnOkClick(new KeyboardUtil.OnOkClick() {
            @Override
            public void onOkClick() {
                updateKeyboard();
                try {
                    double d = Double.valueOf(etInput.getText().toString());
                    if(d<cartGood.getMoq()){
                        etInput.setText(""+cartGood.getMoq());
                        T.toast("问价数量不能小于起订量"+cartGood.getMoq());
                        cartGood.setProductCount(cartGood.getMoq());
                        adapter.notifyDataSetChanged();
                        return;
                    }
                    double min = cartGood.getMoq();
                    double incr =  cartGood.getIncr();
                    double cnt = Double.valueOf(d);

                    incr = incr < 0.01 ? min : incr;

                    if (FormatUtil.isRemainder(cnt,incr,min)) {
                        cnt = FormatUtil.countFormat(cnt,incr,min);
                        etInput.setText(FormatUtil.subZeroAndDot(cnt + ""));
                        etInput.setSelection(etInput.getText().length());

                        //return;
                    }
                   /* if(cnt>99999.99)
                        cnt -= incr;*/



                    adapter.check(fatherPosition,childPosition);
                    cartGood.setProductCount(cnt);
                    adapter.notifyDataSetChanged();
                } catch (Exception e) {
                    e.printStackTrace();
                    T.toast("请检查输入");
                    keyboardUtil.showKeyboard();
                    //updateKeyboard();
                }
            }
        });
        updateKeyboard();
    }
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_btn:
                Integer first = adapter.calAllCheckedStatus().first;
                if(first==0){
                    toast("至少选择1个商品");
                }else {
                    requestOffer();
                }

                break;
            case R.id.iv_box:
            case R.id.tv_all:
                Object tag = ivCheck.getTag();
                if (tag instanceof Boolean) {
                    boolean b = (boolean) tag;
                    tvAll.setTag(!b);
                    ivCheck.setTag(!b);
                    adapter.checkBoxState(!b, ivCheck);
                    adapter.checkAllStatus(!b);
                    adapter.notifyDataSetChanged();
                }
                tvBtn.setText(getString(R.string.offer_d, adapter.calAllCheckedStatus().first));
                break;

        }
    }

    protected View getToolBar() {

        return null;
    }

    protected void initToolbar() {
        rightbtn = (TextView) findViewById(com.epfresh.api.R.id.rightbtn);
        toolbarTitle = (TextView) findViewById(R.id.toolbar_title);

        righticon = (ImageView) findViewById(com.epfresh.api.R.id.righticon);//
        ivBack = (ImageView) findViewById(com.epfresh.api.R.id.baseback);
        tvBack = (TextView) findViewById(com.epfresh.api.R.id.tv_back);
        tvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ivBack.performClick();
            }
        });
        ivBack.setOnClickListener(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        marketId = getIntent().getStringExtra("marketId");
        setContentView(R.layout.activity_offer_list);
        initToolbar();
        toolbarTitle.setText("问价列表");
        ivBack.setVisibility(View.VISIBLE);
       // tvBack.setVisibility(View.VISIBLE);
        //初始化view
        vBottom = findViewById(R.id.ly_bottom);
        vBottom.setVisibility(View.GONE);
        ivCheck = (ImageView) findViewById(R.id.iv_box);

        tvAll = (TextView) findViewById(R.id.tv_all);
        tvBtn = (TextView) findViewById(R.id.tv_btn);

        tvBtn.setOnClickListener(this);

        ivCheck.setOnClickListener(this);
        tvAll.setOnClickListener(this);

        msView = (MultiStateView) findViewById(R.id.ms_view);
        msView.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        msView.setViewForState(R.layout.empty_cart_goods, MultiStateView.VIEW_STATE_EMPTY);
        msView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        View emptyView = msView.getmEmptyView();
        if (emptyView != null) {
            emptyView.findViewById(R.id.tv_btn_cart).setVisibility(View.GONE);
            ((ImageView)emptyView.findViewById(R.id.iv_exception)).setImageResource(R.mipmap.home_often_no);
            ((TextView)emptyView.findViewById(R.id.tv_exception)).setText("没有可问价的商品");
        }
        msView.setOnErrorClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                refresh();
            }
        });
        frameLayout = (PtrMdFrameLayout) findViewById(R.id.ptr);
        lv = (ExpandableListView) findViewById(R.id.lv);
        frameLayout.setPtrHandler(ptrHandler);
        adapter = new OfferExpandListAdapter(OfferListActivity.this, lv, groupList);

        lv.setAdapter(adapter);
        adapter.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long l) {


                if (i < groupList.size()) {
                    OfferMarkBean cartGoods = groupList.get(i);
                    List<OfferMarkBean.ProductListBean> result = cartGoods.getProductList();
                    if (result != null && result.size() > i1) {
                        OfferMarkBean.ProductListBean cartGood = result.get(i1);
//                        String id = cartGood.getProductId();
                        String id = cartGood.getSpecId()+"";
                        Intent intent = new Intent(OfferListActivity.this, DetailGoodsActivity.class);
                        intent.putExtra("storeId", cartGood.getStoreId());
                        intent.putExtra("serviceStoreId",Integer.parseInt(cartGood.getStoreId()));
                        intent.putExtra("id", id + "");
                        startActivity(intent);
                    }
                }
                return true;
            }
        });

        adapter.setOnTextChangeListener(new OfferExpandListAdapter.OnTextChangeListener() {

            @Override
            public void onTextChange(int groupPosition, int childPosition, double lastCnt, OfferMarkBean.ProductListBean cartGood) {
                openOfferDialog(cartGood,groupPosition,childPosition);//groupPosition, childPosition, cartGood);

            }
        });

        adapter.setOnChangeListener(new OfferExpandListAdapter.OnTextChangeListener() {
            @Override
            public void onTextChange(int groupPosition, int childPosition, double lastCnt, OfferMarkBean.ProductListBean cartGood) {
                //calTotalPrice(adapter.calAllCheckedStatus());
//                cntCart(cartGood.getId() + "", cartGood.getCount(), lastCnt);
                //updateCartCnt(lastCnt,cartGood);
               // cartGood.setProductCount(lastCnt);
                adapter.notifyDataSetChanged();
            }
        });

        adapter.setOnCheckChangeListener(new OfferExpandListAdapter.OnCheckChangeListener() {
            @Override
            public void onCheckChange(boolean isCheck, int groupPosition, int childPosition) {

                tvAll.setTag(isCheck);
                ivCheck.setTag(isCheck);
                adapter.checkBoxState(isCheck, ivCheck);
                tvBtn.setText(getString(R.string.offer_d, adapter.calAllCheckedStatus().first));

/*                Pair<Integer, Double> pair = adapter.calAllCheckedStatus();
                //calTotalPrice(pair);

                List<Map<String, Object>> selectedStatus = adapter.getSelectedStatus(groupPosition, childPosition);
                if (selectedStatus != null && selectedStatus.size() > 0) {
                    tvBtn.setText(getString(R.string.offer_d, adapter.calAllCheckedStatus().first));
                }*/
            }
        });

        adapter.setOnNotifyDataSetChangedListener(new OfferExpandListAdapter.OnNotifyDataSetChangedListener() {
            @Override
            public void OnNotifyDataSetChangedListener(int size) {
                boolean b = adapter.checkAllStatus();
                tvAll.setTag(b);
                ivCheck.setTag(b);
                adapter.checkBoxState(b, ivCheck);

                //calTotalPrice(adapter.calAllCheckedStatus());
            }
        });

        refresh();

    }

/*

    private void initView() {

        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        msvGoods = (MultipleStatusView) findViewById(R.id.msv_goods);
        msvGoods.setHint("还没有问价商品");
        LinearLayoutManager layoutManager = new WrapContentLinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        msvGoods.setOnRetryClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reqGoodsList(0);
            }
        });
        initGoodsView();
    }
*/

/*

    LinearLayoutManager layoutManagerGoods;
    private void initGoodsView() {
        initHeadView();
        rvGoods = (RecyclerView) findViewById(R.id.rv_goods);
        layoutManagerGoods = new WrapContentLinearLayoutManager(this);
        layoutManagerGoods.setOrientation(LinearLayoutManager.VERTICAL);
        rvGoods.setLayoutManager(layoutManagerGoods);
        mGoodsAdapter = new MultiTypeAdapter();
        mGoodsBinder = new ViewBinderOfferMy();
        mGoodsBinder.setOnCartAddListener(new ViewBinderOfferMy.OnCartAddListener() {
            @Override
            public void onCartAdd(int type, int position, OfferMyList goods, View v) {
                if (type == 1) {//购物车手动输入
                    openDialog(goods);
                } else if (type == 2) {//添加
                    addCartCnt(v, goods, true);
                } else if (type == 3) {//减少
                    addCartCnt(v, goods, false);
                } else if (type == 10) {
                    openOfferDialog(goods);
                } else if (type == 5) {
                    String id = goods.getSpecId();
                    Intent intent = new Intent(mContext, DetailGoodsActivity.class);
                    intent.putExtra("id", id + "");
                    intent.putExtra("promotionItemId", goods.getPromotionItemId());
                    startActivity(intent);
                }
            }
        });

        mGoodsBinder.setFreshItemListener(new ViewBinderOfferMy.FreshItemListener() {
            @Override
            public void freshItem(int type, int position, OfferMyList goods, View v) {
               requestFreshItem(goods);
            }
        });



        mGoodsAdapter.register(OfferMyList.class, mGoodsBinder);
        LoadMoreViewBinder loadMoreViewBinder = loadMoreDelegate.getLoadMoreViewBinder();
        loadMoreViewBinder.setResourceId(com.epfresh.api.R.layout.common_view_load_more);
        mGoodsAdapter.register(LoadMoreItem.class, loadMoreViewBinder);
        rvGoods.setAdapter(mGoodsAdapter);
        mGoodsAdapter.setItems(mGoods);

        loadMoreDelegate.attach(rvGoods, loadMoreSubject);
    }
*/

    public void emptyView() {


        if (groupList.size() > 0) {
            OfferMarkBean cartGoods = groupList.get(0);
            if (cartGoods != null && (cartGoods.getProductList() == null || cartGoods.getProductList().size() == 0)) {
                msView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
                vBottom.setVisibility(View.GONE);
            } else {
                msView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                vBottom.setVisibility(View.VISIBLE);
                showTips();
                //vBottom.setVisibility(View.GONE);
            }
        } else {
            msView.setViewState(MultiStateView.VIEW_STATE_EMPTY);
            vBottom.setVisibility(View.GONE);
        }
    }


    OnRequestListener<ContentEntity<OfferMarkBean>> onCartRequestListener = new OnRequestListener<ContentEntity<OfferMarkBean>>() {
        @Override
        public ContentEntity<OfferMarkBean> jsonToObj(String s) {
            Log.e("ESD","获取的问价列表s="+s);
            return new Gson().fromJson(s, new TypeToken<ContentEntity<OfferMarkBean>>() {
            }.getType());
        }

        @Override
        public void onFail(int i, Object o, Object o1) {
            frameLayout.refreshComplete();
            if (groupList.size() == 0) {
                msView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                vBottom.setVisibility(View.GONE);
            }
        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {
            frameLayout.refreshComplete();

            if (groupList.size() == 0) {
                msView.setViewState(MultiStateView.VIEW_STATE_ERROR);
                vBottom.setVisibility(View.GONE);
            }
        }

        @Override
        public void onStart(Object o) {
            if (!frameLayout.isRefreshing())
                msView.setViewState(MultiStateView.VIEW_STATE_LOADING);
            if (groupList.size() == 0) {
                vBottom.setVisibility(View.GONE);
            }
        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<OfferMarkBean>> responseEntity, Object o) {
            frameLayout.refreshComplete();
            ContentEntity<OfferMarkBean> responseElement = responseEntity.getResponseElement();
            Log.d("listShoppingCar",(responseElement != null)+"");
            if (responseElement != null) {
                List<OfferMarkBean> content = responseElement.getMarkList();
                if (content != null) {
                    groupList.clear();


                    int size = 0;

                    for (int i = 0; i < content.size(); i++) {
                        OfferMarkBean cartGoods = content.get(i);
                        List<OfferMarkBean.ProductListBean> result = cartGoods.getProductList();
                        if (result != null && result.size() > 0) {

                            size += result.size();
                            groupList.add(cartGoods);
                        }
                    }

                    adapter.notifyDataSetChanged();
                    adapter.checkStatus();
//                    DataManager.getInstance().setCartCntStatus(size);

                    DataManager.getInstance().updateCartCnt();
                }

            }

            emptyView();

        }
    };

    public void requestCartList() {

        if (ApplicationHelper.getInstance().getUser().getAccess_token() == null || "".equals(ApplicationHelper.getInstance().getUser().getAccess_token())) {
            return;
        }
        RequestEntityMap re = new RequestEntityMap();
        //re.setCmd("purchaser/offer/product/list");appOrder/listShoppingCar
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_offer_list);
        re.putParameter("cityId", ApplicationHelper.getInstance().getCity().getCityId());
        if(marketId!=null&&!"".equals(marketId))
            re.putParameter("marketId", marketId);
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_order_offer_list, onCartRequestListener);
    }
    public class Param {
        private int productSpecId;
        private String quantity;
        public int getProductSpecId() {
            return productSpecId;
        }

        public void setProductSpecId(int productSpecId) {
            this.productSpecId = productSpecId;
        }

        public String getQuantity() {
            return quantity;
        }

        public void setQuantity(String quantity) {
            this.quantity = quantity;
        }
    }
    public void requestOffer() {
        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_addProductOffer);
        ArrayList list = new ArrayList();
        for(int i=0;i<groupList.size();i++) {
            for (int j = 0; j < groupList.get(i).getProductList().size(); j++) {
                if (groupList.get(i).getProductList().get(j).isSelect()) {
                    OfferMarkBean.ProductListBean bean = groupList.get(i).getProductList().get(j);
                    Param param = new Param();
//                    param.setProductSpecId(bean.getProductId());
                    param.setProductSpecId(bean.getSpecId());
                    param.setQuantity("" + bean.getProductCount());
                    list.add(param);
                }
            }
        }
        if(list.size()<=0) {
            toast("至少选择1个商品");
            return;
        }
        re.putParameter("productOffers",list);
        request(re, com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_offer_addProductOffer, new OnRequestListener<List<OfferDtoBean>>() {
            @Override
            public List<OfferDtoBean> jsonToObj(String s) {
                Log.e("ESD","提交问价结果s="+s);
                return new Gson().fromJson(s, new TypeToken<List<OfferDtoBean>>() {
                }.getType());
            }

            @Override
            public void onFail(int i, Object o, Object o1) {
                hideProgressDialog();
            }

            @Override
            public void onResponseError(int i, Object o1, Object o) {
                hideProgressDialog();
            }

            @Override
            public void onStart(Object o) {
                showProgressDialog();
            }

            @Override
            public void onResponse(ResponseEntity<List<OfferDtoBean>> responseEntity, Object o) {
                hideProgressDialog();
                finish();
            }
        });

    }
    @Override
    public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            ivBack.performClick();
        }
        return false;
    }



    public void addCartCnt(View v,OfferMyList goods, boolean isAdd) {
        double min = goods.getMoq();
        double incr = goods.getIncr();
        double amount = goods.getCount();


        if (isAdd) {
            amount = FormatUtil.countAdd(amount, incr);
        } else {
            amount = FormatUtil.countAdd(amount, -incr);
        }


//        amount = FormatUtil.countFormat(amount, incr, min);
        amount = FormatUtil.countFormat(amount, incr, min, goods.getInventory());

    }
    OfferTipsDialog upGoodsTipsDialog;

    public void showTips() {
        SharedPreferences sp = getSharedPreferences("tips_show_offer" + ApplicationHelper.getInstance().getUser().getAccountId(), Context.MODE_PRIVATE);

        if (0 == sp.getInt("tips_number", 0)) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putInt("tips_number", 1);
            editor.commit();

            vBottom.post(new Runnable() { @Override public void run() {
                int[] location = {0,0};
                vBottom.getLocationOnScreen(location);
                if (upGoodsTipsDialog == null)
                    upGoodsTipsDialog = new OfferTipsDialog(OfferListActivity.this,location);
                if (!upGoodsTipsDialog.isShowing())
                    upGoodsTipsDialog.show();
            } });

        }
    }
}
